/**
 * @Date: 2021-08-28 13:14:23
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName: setEchartFrontSize
 * @Description:
 * @Return:
 */
import moment from 'moment';
import { $http, getInterfaceIsLoginData, getInterfaceIpData, getInterfaceMonitorData } from '@/untils/axios/request';
import config from '@/untils/axios/config';
import store from '@/store/index';

//当前视口宽度
function $nowSize(val, initWidth = 1920) {
    let nowClientWidth = document.documentElement.clientWidth;
    return val * (nowClientWidth / initWidth);
}

/**
 * @Date: 2021-08-29 19:14:53
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName: getDateObj
 * @Description: 返回传入的日期对象数据
 * @Return:
 * @param {*} moment: $moment()
 */
function $getDateObj(chooseMoment) {
    const nowTime = moment();
    return {
        choose: {
            // 所选时间
            dateStr6: chooseMoment.format('YYYYMM'), // 格式化年月日
            dateStr8: chooseMoment.format('YYYYMM') === nowTime.format('YYYYMM') ? nowTime.format('YYYYMMDD') : chooseMoment.format('YYYYMMDD'), // 格式化年月日
            year: chooseMoment.get('year'), // 年
            month: chooseMoment.get('month') + 1, // 月 1:1月 12:12月
            daysInMonth: chooseMoment.daysInMonth(), // 日
            timestamp: chooseMoment.valueOf(), // 日期的时间戳
            week:
                chooseMoment.format('YYYYMM') === nowTime.format('YYYYMM')
                    ? nowTime.isoWeekday() // 周几
                    : chooseMoment.isoWeekday(), // 周几
            lastDayWeek:
                // endOf会影响nowTime 这里不能用nowTime
                chooseMoment.format('YYYYMM') === nowTime.format('YYYYMM')
                    ? moment()
                          .endOf('month')
                          .isoWeekday() // 所选时间最后一天的周几
                    : chooseMoment.endOf('month').isoWeekday(), // 所选时间最后一天的周几
        },
        now: {
            // 当前系统时间
            dateStr6: nowTime.format('YYYYMM'), // 格式化年月日
            dateStr8: nowTime.format('YYYYMMDD'), // 格式化年月日
            year: nowTime.get('year'), // 年
            month: nowTime.get('month') + 1, // 月
            day: nowTime.get('date'), // 日
            befDay: nowTime.get('date') - 1, // 日
            daysInMonth: nowTime.daysInMonth(), // 日期的总天数
            timestamp: nowTime.valueOf(), // 日期的时间戳
            week: nowTime.isoWeekday(), // 周几
        },
        isNow: chooseMoment.format('YYYYMM') === nowTime.format('YYYYMM'),
    };
}

/**
 * @Date: 2021-09-01 10:49:29
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName:
 * @Description: 就项目移过来的
 * @Return:
 * @param {*} data
 * @param {*} type
 * @param {*} typeVal
 * @param {*} toFixed
 */
const $dataProcess = (data, type, typeVal, toFixed) => {
    let num, unit;
    if (data !== '' && data !== null && data !== undefined && data !== '--') {
        // if (data.indexOf(",") != -1) {
        var reg = /^-?[0-9]+.?[0-9]*/; //是否为数字
        //如果是数字
        if (reg.test(data)) {
            if (type === 'money') {
                if (typeVal === 'tenth') {
                    // if(data>0 && data<100){
                    //     num = '<0.01'
                    //     unit = '万'
                    // }else
                    if (data == null) {
                        num = '';
                    } else {
                        num = (data / 10000).toFixed(1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                        unit = '万';
                    }
                } else {
                    num = (data / 10000).toFixed(1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                    unit = '万';
                }
            } else if (type === 'moneyTwo') {
                num = (data / 10000).toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '万';
            } else if (type === 'moneyThree') {
                num = (data / 10000).toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '万';
            } else if (type === 'percent') {
                if (typeVal === 'chartPercent') {
                    num = (data * 100).toFixed(1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                    unit = '%';
                } else if (data == null) {
                    num = '';
                } else {
                    num = (data * 100).toFixed(1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                    unit = '%';
                }
            } else if (type === 'newpercent') {
                num = (data * 100).toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '%';
            } else if (type === 'percentNumber') {
                num = (data * 100).toFixed(1);
                unit = '%';
            } else if (type === 'day') {
                num = (data / 1).toFixed(1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '天';
            } else if (type === 'stock') {
                num = (data / 10000).toFixed(1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '万件';
            } else if (type === 'danStock') {
                num = (data / 1).toFixed(typeof toFixed !== 'undefined' ? toFixed : 1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '件';
            } else if (type === 'time') {
                num = (data / 1).toFixed(1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '小时/单';
            } else if (type === 'home') {
                num = (data / 1).toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
            } else if (type === 'chartPercent') {
                num = (data * 100).toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '%';
            } else if (type === 'chartMoney') {
                num = (data / 10000).toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '元';
            } else if (type === 'chartAveragePerson') {
                num = (data / 10000).toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '万/人';
            } else if (type === 'number') {
                num = (data / 10000).toFixed(1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '万';
            } else if (type === 'family') {
                num = (data / 1).toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '家';
            } else if (type === 'averagePerson') {
                num = (data / 10000).toFixed(1).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '万/人';
            } else if (type === 'person') {
                num = (data / 1).toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '人';
            } else if (type === '') {
                num = data;
                unit = '';
            } else {
                num = (data / 1).toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, '$1,');
                unit = '';
            }
            return {
                num,
                unit,
            };
        } else {
            num = data;
            unit = '';
        }
    } else {
        num = '--';
        unit = '';
    }
    return {
        num,
        unit,
    };
};

/**
 * @Date: 2021-07-15 09:53:57
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName: $deepCloneFun
 * @Description: 深拷贝
 * @Return: obj
 */
const $deepCloneFun = (obj, hash = new WeakMap()) => {
    const isComplexDataType = obj => (typeof obj === 'object' || typeof obj === 'function') && obj !== null;

    if (obj.constructor === Date) return new Date(obj); // 日期对象直接返回一个新的日期对象
    if (obj.constructor === RegExp) return new RegExp(obj); //正则对象直接返回一个新的正则对象

    //如果循环引用了就用 Map 来解决
    if (hash.has(obj)) return hash.get(obj);

    let allDesc = Object.getOwnPropertyDescriptors(obj);

    //遍历传入参数所有键的特性
    let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);

    //继承原型链
    hash.set(obj, cloneObj);
    for (let key of Reflect.ownKeys(obj)) {
        cloneObj[key] = isComplexDataType(obj[key]) && typeof obj[key] !== 'function' ? $deepCloneFun(obj[key], hash) : obj[key];
    }
    return cloneObj;
};

/**
 * @Date: 2021-07-15 16:03:09
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName: $setTotlaChildrenKey
 * @Description: 修改数组的key(如果数组内有children循环对children加key)
 * @Return: Array
 * @param {*} arr
 * @param {*} keyName
 * @param {*} deep  // 默认开启深拷贝
 */
const $setChildrenKey = (arr, keyName = '', deep = true) => {
    arr = arr.map((item, index) => {
        item.key = keyName ? keyName + '-' + index : keyName;
        if (item.children && item.children.length) item.children = $setChildrenKey(item.children, item.key + '-child-');
        return deep ? $deepCloneFun(item) : item;
    });
    return arr;
};

/**
 * @Date: 2021-09-14 13:18:11
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName: verifyLogin
 * @Description: 验证登录
 * @Return:
 */
const $getInterfaceIsLoginData = async () => {
    let userLogin = false;
    let userInfo;
    if (!store.state.userInfo) {
        const res = await getInterfaceIsLoginData({}, 'getInterfaceIsLoginData');

        if (res && res.code == 200) {
            userLogin = true;
            userInfo = res.data;
        } else {
            // 这里需要做重定向
        }
    } else {
        userInfo = store.state.userInfo;
    }

    return { userLogin, userInfo };
};

/**
 * @Date: 2021-09-15 13:14:05
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName:
 * @Description:获取用户角色权限
 * @Return:
 */

const $getUserJurisdiction = async loginName => {
    const res = await $http({}, 'getUserJurisdiction', {
        url: config.roleUrl + `?user_code=${loginName}`,
        method: 'POST',
    });
    return res?.data;
};

/**
 * @Date: 2021-09-15 18:15:33
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName:
 * @Description:
 * @Return:
 */
const $getUserDataJurisdiction = async (loginName, dataType) => {
    const res = await $http({}, 'getUserJurisdiction', {
        url: config.roleDataUrl + `?user_code=${loginName}&data_type=${dataType}`,
        method: 'POST',
    });
    return res?.data;
};

/**
 * @Date: 2021-09-16 13:16:42
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName: $verifyDataPermissions
 * @Description:根据serviceId和对应的des名称去做验证权限
 * @Return:
 * arr : 数据源

 * 需要验证的模块 以及部分下拉
 * - 销量目标达成二级 service_scm_midplan_sales ,  getTableList
 * - 销售计划提报量执行率二级 service_scm_midplan_submit_rate, getTableList
 * - 计划准确率二级 service_scm_midplan_target_achieve_plan_rate, getTargetDetailSales
 * - 拖欠订单二级 service_scm_midplan_overorder, 
 * - 月度分析二级 service_scm_midplan_analysis , getFirstData,getNextData
 * */
const $verifyDataPermissions = (arr, serviceId, funName) => {
    let { userRoleDataJurisdiction, userDataType } = store.state.userInfo;

    let targetName;

    let funNameArr = [];

    let newArr = [];

    let verificationServiceIdArr = ['service_scm_midplan_sales', 'service_scm_midplan_submit_rate', 'service_scm_midplan_target_achieve_plan_rate', 'service_scm_midplan_overorder', 'service_scm_midplan_analysis', 'service_scm_midplan_target_achieve_plan_rate', 'service_scm_midplan_overorder'];

    funNameArr = ['getTableList', 'getTargetDetailSales', 'getSalesOne', 'getFirstData', 'getNextData', 'getTop10SKU', 'getMultipleSelectList', 'getTargetDetailSales', 'getCategoryList', 'getSalesOne', 'getSalesAllThree'];

    targetName = 'SALES_DEPARTMENT_NAME';

    if (userDataType.indexOf('全部') !== -1) return arr; // 可查所有数据

    // 根据服务id+方法名 确认对应接口才进行验证

    if (verificationServiceIdArr.indexOf(serviceId) === -1 || funNameArr.indexOf(funName) === -1) return arr;

    if (userRoleDataJurisdiction) {
        // 这里是客户和KA的
        if (userDataType.indexOf('KA系统') !== -1) {
            let isHaveKA = false;

            for (let i in userRoleDataJurisdiction) {
                if (userRoleDataJurisdiction[i].data_role_name === 'KA系统') {
                    isHaveKA = true;
                    break;
                }
            }

            if (!isHaveKA) {
                userRoleDataJurisdiction.push({
                    data_role_name: 'KA系统',
                });
            }
        }

        let data_role_nameArr = userRoleDataJurisdiction
            .filter(item => {
                if (item.data_role_name === 'KA系统') item.data_role_name = 'KA';
                return item;
            })
            .map(item => item.data_role_name);

        arr.map(item => {
            if (data_role_nameArr.indexOf(item[targetName]) !== -1) newArr.unshift(item);
        });
    }

    if (userDataType.length) {
        // 这里是非客户和KA的
        if (userDataType.indexOf('电商') !== -1 || userDataType.indexOf('商用') !== -1 || userDataType.indexOf('海外') !== -1) {
            targetName = 'SALES_DEPARTMENT_NAME';
            arr.map(item => {
                if (userDataType.indexOf(item[targetName]) !== -1) newArr.unshift(item);
            });
        }
    }
    return newArr;
};

/**
 * @Date: 2021-09-27 09:37:39
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName: $isKAorCustomer
 * @Description: 判断是否KA或者是客户
 * @Return:
 */
const $isKAorCustomer = userRoleJurisdiction => {
    let userDataType = [];

    userRoleJurisdiction.map(item => {
        switch (item.post_role_code) {
            case 'POST_SC_CHANNEL_GT':
                userDataType.push('省区');
                break;
            case 'POST_SC_CHANNEL_KA':
                userDataType.push('KA系统');
                break;
            case 'POST_SC_CHANNEL_EC':
                userDataType.push('电商');
                break;
            case 'POST_SC_CHANNEL_BU':
                userDataType.push('商用');
                break;
            case 'POST_SC_CHANNEL_OS':
                userDataType.push('海外');
                break;
            case 'POST_SC_CHANNEL_ALL':
                userDataType.push('全部');
                break;
        }
        return item;
    });

    return { userDataType };
};

/**
 * @Date: 2021-09-27 15:14:53
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName:
 * @Description: 获取浏览器信息
 * @Return:
 */
const $getExplorerInfo = () => {
    return {
        type: navigator.vendor, //浏览器内核
        version: navigator.appVersion, //浏览器版本
        system: navigator.platform, //系统平台
    };
};

/**
 * @Date: 2021-09-27 09:38:10
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName: $setMonitorDayFun
 * @Description: 埋点监控
 * @Return:
 */
const $setMonitorDayFun = async (userInfo, titleName) => {
    let { loginName, nickName } = userInfo;

    let getInterfaceIpDataRes = await getInterfaceIpData();

    let ipArr = getInterfaceIpDataRes ? getInterfaceIpDataRes.split(',') : [];

    if (!store.state.publicMonitorData) {
        const publicMonitorData = {
            B_USER_ID: loginName, //账号
            B_USER_NAME: nickName, //用户名
            B_USER_IP: ipArr[0] || '', //IP
            B_TERMINAL_TYPE: $getExplorerInfo().type, //终端类型(TYPE)
            B_TERMINAL_VERSION: $getExplorerInfo().version, //终端版本(VERSION)
            B_APP_PLATFORM: '数略云大屏', //应用平台(PLATFORM)
            B_APP_SYSTEM: $getExplorerInfo().system, //系统类型(SYSTEM)
            B_PAGE_PATH: titleName, //页面路径
            B_APP_MODEL: '中台计划驾驶舱', //专题名称(topic)
            B_APP_NAME: '中台计划驾驶舱',
        };
        store.commit('setPublicMonitorData', publicMonitorData);
    }

    let turnMonitorData = Object.assign(store.state.turnMonitorData, {
        B_APP_PAGE: titleName, //页面名称
    });

    if (titleName.includes('首页')) {
        $getMonitorDayFun(turnMonitorData, '登录');
    } else {
        $getMonitorDayFun(turnMonitorData, '跳转');
    }
};

/**
 * @Date: 2021-09-27 16:27:17
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName:
 * @Description: 旧方法~
 * @Return:
 */
const $objectToString = data => {
    let newdata = JSON.stringify(data).replace(/,/g, '|'); //全局替换，为|
    newdata = newdata.substr(1); //删除第一个字符
    let newresult = newdata.substr(0, newdata.length - 1); //删除最后一个字符
    return newresult;
};

//处理埋点接口函数
const $getMonitorDayFun = async (data, logType) => {
    let logLevel = process.env.NODE_ENV == 'prd' ? 'INFO' : 'DEBUG';
    let NewMonitorData = data;
    //获取全局变量
    let publicMonitorData = store.state.publicMonitorData;
    let content = '';
    //监控数据-合并对象转为字符串
    if (data != '') {
        content = $objectToString(Object.assign(NewMonitorData, publicMonitorData));
    } else {
        content = $objectToString(Object.assign(publicMonitorData));
    }
    let monitorParams = {
        appID: 'supply-midplan-view', //应用ID
        logType, //日志分类
        logLevel, //日志级别
        operator: publicMonitorData.B_USER_NAME, //操作人
        content: content, //日志内容
    };
    /* 调用埋点接口-插入数据到数据库 */
    getInterfaceMonitorData(monitorParams, 'monitor').then(() => {});
};

/**
 * @Date: 2021-09-29 14:07:24
 * @Author: hejiajun
 * @LastEditors: hejiajun
 * @FunName: $compareDatSort
 * @Description: 中文排序,按照比较(compareDatArr)的顺序去排序
 * @Return: Array (按照compareDat的顺序输出)
 * "Params": {
 *    sourceDataArr:Array 数据源
 *    compareDatArr:Array || String 比较体/获取传入字符串(channel,brand,category)
 * },
 * demo:
 * sourceDataArr = ['海外','商用','电商','KA','客户']
 * compareDat = {
 *    "客户":1,
 *    "KA" :2,
 *    "电商":3,
 *    "商用":4,
 *    "海外":5,
 * }
 *
 */

const $compareDatSort = (sourceDataArr, compareDatArr, targetName) => {
    if (!compareDatArr) return console.error('请传入compareDatArr');

    if (typeof compareDatArr === 'string') {
        switch (compareDatArr) {
            case 'channel':
                compareDatArr = {
                    全部: 0,
                    客户: 1,
                    KA: 2,
                    电商: 3,
                    商用: 4,
                    海外: 5,
                };
                break;
            case 'brand':
                // 雷达图不能使用 因为默认显示是逆时针的需要单独改
                compareDatArr = {
                    好爸爸品牌: 1,
                    立白品牌: 2,
                    洁多芬品牌: 3,
                    立网品牌: 4,
                    商用品牌: 5,
                    新品牌: 6,
                };
                break;
            case 'category':
                // 雷达图不能使用 因为默认显示是逆时针的需要单独改
                compareDatArr = {
                    洗衣粉: 1,
                    洗洁精: 2,
                    洗衣皂: 3,
                    洗衣液: 4,
                    柔顺剂: 5,
                    漂渍液: 6,
                };
                break;
        }
    }

    let arr = [];

    arr = sourceDataArr.sort((a, b) => {
        if (targetName) {
            return compareDatArr[a[targetName]] - compareDatArr[b[targetName]];
        } else {
            return compareDatArr[a] - compareDatArr[b];
        }
    });

    return arr;
};

export default {
    $nowSize,
    $getDateObj, // 获取日期对象
    $dataProcess,
    $setChildrenKey, // 设置子数据的key值
    $deepCloneFun, // 深拷贝
    $getInterfaceIsLoginData, // 验证登录
    $getUserJurisdiction, // 获取用户角色权限
    $getUserDataJurisdiction, // 获取用户角色数据权限
    $verifyDataPermissions, //
    $isKAorCustomer, // 判断是否KA还是客户渠道
    $setMonitorDayFun, // 设置路由埋点
    $objectToString,
    $compareDatSort, // 中文排序,按照比较(compareDatArr)的顺序去排序
};
